package com.ozo.boot.auth.log;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ozo.boot.system.pojo.dto.SysLoginLogDTO;
import jakarta.servlet.http.HttpServletRequest;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * 登录事件工具类
 *
 * @author qiangesoft
 * @since 2024-07-11
 */
public class LoginLogUtil {

    /**
     * 登录成功
     *
     * @param username
     * @param responseMsg
     * @return
     */
    public static SysLoginLogDTO success(String username, String responseMsg) {
        SysLoginLogDTO loginLogDTO = new SysLoginLogDTO();
        loginLogDTO.setUsername(username);
        loginLogDTO.setSuccessFlag(true);
        loginLogDTO.setResponseMsg(responseMsg);
        loginLogDTO.setLoginTime(LocalDateTime.now());
        getIPLocation(loginLogDTO);
        return loginLogDTO;
    }

    /**
     * 登录失败
     *
     * @param username
     * @param responseMsg
     * @return
     */
    public static SysLoginLogDTO fail(String username, String responseMsg) {
        SysLoginLogDTO loginLogDTO = new SysLoginLogDTO();
        loginLogDTO.setUsername(username);
        loginLogDTO.setSuccessFlag(false);
        loginLogDTO.setResponseMsg(responseMsg);
        loginLogDTO.setLoginTime(LocalDateTime.now());
        getIPLocation(loginLogDTO);
        return loginLogDTO;
    }

    /**
     * 获取ip和位置
     *
     * @param loginLogDTO
     */
    private static void getIPLocation(SysLoginLogDTO loginLogDTO) {
        // 位置信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddr = JakartaServletUtil.getClientIP(request);
        loginLogDTO.setRequestIp(ipAddr);
        IpInfo ipInfo = SpringUtil.getBean(Ip2regionSearcher.class).memorySearch(ipAddr);
        if (ipInfo != null) {
            loginLogDTO.setRequestLocation(StringUtils.isNotBlank(ipInfo.getCountry()) ? ipInfo.getCountry() + ipInfo.getProvince() + ipInfo.getCity() + ipInfo.getIsp() : ipInfo.getIsp());
        }
    }

}
